//
//  LanguageTool.m
//  ZiJinLian
//
//  Created by 🐛 on 2018/1/3.
//  Copyright © 2018年 lzy. All rights reserved.
//


#import "AppDelegate.h"
#import "LanguageTool.h"
static LanguageTool *sharedModel;
@interface LanguageTool()

@property(nonatomic,strong)NSBundle *bundle;
@property(nonatomic,copy)NSString *language;

@end

@implementation LanguageTool
+(id)sharedInstance
{
    if (!sharedModel)
    {
        sharedModel = [[LanguageTool alloc]init];
    }
    
    return sharedModel;
}

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        [self initLanguage];
    }
    
    return self;
}

-(void)initLanguage
{
    NSString *tmp = [[NSUserDefaults standardUserDefaults]objectForKey:LANGUAGE_SET];
    NSString *path;
    if (tmp==nil) {
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        
        NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
        
        NSString * preferredLang = [allLanguages objectAtIndex:0];
        if ([preferredLang isEqualToString:@"zh-Hans-CN"]) {
            tmp=CNS;
        }else if ([preferredLang isEqualToString:@"bo-CN"]){
            tmp=EN;
        }else {
            NSLog(@"当前语言:%@", preferredLang);
        }
        [[NSUserDefaults standardUserDefaults]setObject:DEFAULT forKey:LANGUAGE_DEFAULT];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    
    self.language = tmp;
    path = [[NSBundle mainBundle]pathForResource:self.language ofType:@"lproj"];
    self.bundle = [NSBundle bundleWithPath:path];
}

-(NSString *)getStringForKey:(NSString *)key withTable:(NSString *)table
{
    if (self.bundle)
    {
        return NSLocalizedStringFromTableInBundle(key, table, self.bundle, @"");
    }
    
    return NSLocalizedStringFromTable(key, table, @"");
}

-(void)changeNowLanguage:(NSString*)language;
{
//    if ([self.language isEqualToString:EN])
//    {
//        [self setNewLanguage:CNS];
//    }
//    else
//    {
//        [self setNewLanguage:EN];
//    }
    [self setNewLanguage:language];
}

-(void)setNewLanguage:(NSString *)language
{
//    if ([language isEqualToString:self.language])
//    {
//        return;
//    }
    
    if ([language isEqualToString:EN] || [language isEqualToString:CNS])
    {
        NSString *path = [[NSBundle mainBundle]pathForResource:language ofType:@"lproj"];
        self.bundle = [NSBundle bundleWithPath:path];
    }
    
    self.language = language;
    [[NSUserDefaults standardUserDefaults]setObject:language forKey:LANGUAGE_SET];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [self resetRootViewController];
}

//重新设置
-(void)resetRootViewController
{
    MianTabBarViewController *tabVC = [[MianTabBarViewController alloc] init];
    AppDelegate *appDelegate =
    (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.window.rootViewController=tabVC;
    [appDelegate.window makeKeyAndVisible];
}

@end
